package com.netease.musicweekly.android.widget;

import com.netease.musicweekly.entity.Article;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class ArticleWebView extends WebView {

	public static final String TAG = "ArticleWebView";

	private static GestureDetector mGestureDetector;

	private Article article;

	public ArticleWebView(Context context) {
		this(context, null);
	}

	public ArticleWebView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ArticleWebView(Context ctxt, AttributeSet attrs, int defStyle) {
		super(ctxt, attrs, defStyle);
		mGestureDetector = getGestureDetector(ctxt);
		getSettings().setSavePassword(false);
		getSettings().setSaveFormData(false);
		getSettings().setJavaScriptEnabled(true);
		getSettings().setSupportZoom(false);
		setWebChromeClient(new MyWebChromeClient());
		addJavascriptInterface(new Object() {
			public String getTitle() {
				return getArticle().title;
			}

			public String getBody() {
				return getArticle().body;
			}
		}, "article");
	}

	private GestureDetector getGestureDetector(Context context) {
		if (mGestureDetector == null) {
			ToolbarTapGestureListener gestureListener = new ToolbarTapGestureListener();
			mGestureDetector = new GestureDetector(context, gestureListener);
		}
		return mGestureDetector;
	}

	public boolean onTouchEvent(MotionEvent me) {
		mGestureDetector.onTouchEvent(me);
		return super.onTouchEvent(me);
	}

	public void onTextDecreaseSize() {
		loadUrl("javascript:decreaseSize()");
	}

	public void onTextIncreaseSize() {
		loadUrl("javascript:increaseSize()");
	}

	public void setArticle(Article article) {
		this.article = article;
	}

	public Article getArticle() {
		return article;
	}

	class ToolbarTapGestureListener extends
			GestureDetector.SimpleOnGestureListener {
		public boolean onDoubleTap(MotionEvent me) {
			return false;
		}

		public boolean onDoubleTapEvent(MotionEvent me) {
			return false;
		}

		public boolean onSingleTapUp(MotionEvent me) {
			if (ToolbarProvider.getInstance().getToolbar() != null)
				ToolbarProvider.getInstance().getToolbar().onTap();
			return false;
		}
	}

	/**
	 * Provides a hook for calling "alert" from javascript. Useful for debugging
	 * your javascript.
	 */
	class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				JsResult result) {
			Log.d(TAG, message);
			result.confirm();
			return true;
		}
	}
}
